import sys
import os

"""
封装配置
"""
from albertv0 import *

from common.read_file import read_json
from common.utils import get_current_path, get_dict
from common.log import LogUtil
from common.query_model import QueryModel as CommonQueryModel


def init_module(current_module):
    # init_file_path = sys._getframe(1).f_code.co_filename
    # root_path = get_current_path(init_file_path)
    root_path = get_current_path(os.path.abspath(current_module.__file__))
    sys.path.append(root_path)
    current_module.Main = current_module.main.Main
    init_query_model(current_module)

    plugin_path = root_path + '/plugin.json'
    config = read_json(plugin_path)
    current_module.config = config

    current_module.__iid__ = config['ID']
    current_module.__prettyname__ = config['Name']
    current_module.__version__ = config['Version']
    current_module.__trigger__ = config['ActionKeyword'] + ' '
    current_module.__author__ = config['Author']
    current_module.__dependencies__ = [config['Description']]
    info(root_path + config['IconPath'])
    current_module.iconPath = iconLookup(root_path + config['IconPath'])
    pass


def init_query_model(current_module):
    """
    初始化查询model 允许用户自定义查询model
    若无自定义 则使用common下的current_module
    :param current_module:
    :return:
    """
    if 'query_model' in dir(current_module) and 'QueryModel' in dir(current_module.query_model):
        current_module.QueryModel = current_module.query_model.QueryModel
        pass
    else:
        current_module.QueryModel = CommonQueryModel
        pass
    pass


def handleQuery(query, current_module):
    main_class = current_module.Main
    query_model_class = current_module.QueryModel
    query_model = query_model_class(query.trigger, query.string)
    main_class.before_query(query_model)
    if not query.isTriggered:
        results = None
    else:
        try:
            rs = main_class.handle_query(query_model)
            if rs is None or len(rs) == 0:
                results = Item(
                    id=current_module.__prettyname__,
                    icon=current_module.iconPath,
                    text='no result',
                    subtext="please check you input...",
                )
            else:
                if isinstance(rs, dict):
                    rs = [rs]
                results = []
                for i in range(len(rs)):
                    _rs = rs[i]
                    item = Item(
                        id=current_module.__prettyname__,
                        icon=current_module.iconPath,
                        text=get_dict(_rs, 'text'),
                        subtext=get_dict(_rs, 'subtext'),
                        completion=get_dict(_rs, 'completion'),
                        actions=get_dict(_rs, 'actions')
                    )
                    results.append(item)
                    pass
                pass
            pass
        except Exception as e:
            import traceback
            info(traceback.format_exc())
            LogUtil.info(traceback.format_exc())
            results = Item(
                id=current_module.__prettyname__,
                icon=current_module.iconPath,
                text='查询异常',
                subtext="查询系统运行日志 日志位置 [扩展位置]/modules/common/albert.log",
            )
            pass
    main_class.after_query(query_model)
    return results
    pass
